library(plyr)
library(dplyr)
library(lme4)
library(reshape2)
library(lattice)
library(latticeExtra)
library(MASS)
library(MCMCglmm)
library(ordinal)
library(brms)

#we collected the data on two different days and thus have two different files we need to combine
df <- read.csv("pollExpInstr (accessed 2018-11-15)OLD.csv")
df2 <- read.csv("pollExpInstr (accessed 2018-11-16).csv")
df <- rbind(df,df2)

df <- subset(df, df$participant._index_in_pages == 21) #those participated, the others were not allowed to continue
df$survey <- ifelse(df$player.survey == 1, "survey", "no-survey") 
df$threshold <- factor(
                      ifelse(df$player.threshold == 1, "threshold", ifelse(df$player.threshold == 0,"no-threshold","majority-rule") ),
                      levels = c( "no-threshold","threshold", "majority-rule")
                      )
df$treatment <- sprintf("%s-%s",df$survey,df$threshold)
df$minorityImmigration <- ifelse(df$player.immigration == 1, T, F)
df$minorityEnvironment <- ifelse(df$player.environment == 2, T, F)
df$minorityFirearms<- ifelse(df$player.firearms == 0, T, F)
df$minorityFamilies <- ifelse(df$player.families == 0, T, F)

df$middleImmigration <- ifelse(df$player.immigration == 0, T, F)
df$middleEnvironment <- ifelse(df$player.environment == 0, T, F)
df$middleFirearms<- ifelse(df$player.firearms == 1, T, F)
df$middleFamilies <- ifelse(df$player.families == 1, T, F)

df$majorityImmigration <- ifelse(df$player.immigration == 2, T, F)
df$majorityEnvironment <- ifelse(df$player.environment == 1, T, F)
df$majorityFirearms<- ifelse(df$player.firearms == 2, T, F)
df$majorityFamilies <- ifelse(df$player.families == 2, T, F)

aggregate(data=df, participant.code ~ treatment, FUN = length)

#sample is left skew
hist(df$player.pol, breaks=-1:10)

#we have to restructure the data to make sure that we have one row per vote
restructured <- data.frame(c(df$minorityImmigration,df$minorityEnvironment,df$minorityFirearms,df$minorityFamilies),
                           c(df$middleImmigration,df$middleEnvironment,df$middleFirearms,df$middleFamilies),
                           c(df$majorityImmigration,df$majorityEnvironment,df$majorityFirearms,df$majorityFamilies),
                           rep(df$threshold,4),
                           rep(df$survey,4),
                           rep(c("Immigration","Environment","Firearms","Families"),each = length(df$minorityImmigration)),
                           rep(df$participant.code, 4),
                           rep(df$player.age,4),
                           rep(df$player.pol,4),
                           rep(as.factor(df$player.sex),4)
                           )
colnames(restructured) <- c("minority","middle","majority","threshold","survey","question","subject","age","pol","sex")
restructured$voteValue <- factor(
                                ifelse(restructured$minority, "minority", ifelse(restructured$middle, "middle", "majority")),
                                       levels = c("minority","middle","majority")
                                )

aggregate(data=restructured, minority ~ survey + question, FUN = mean)

#of the 4 political issues that could receive the money, we selected environment randomly, 
# which because of the vote and electoral system resulted in paying 
# 30$ to Heartland, 203$ to Greenpeace and 967$ to National Wildlife Federation
aggregate(data=restructured, minority ~ threshold + question, FUN = mean)
aggregate(data=restructured, middle ~ threshold + question, FUN = mean)
aggregate(data=restructured, majority ~ threshold + question, FUN = mean)
table(restructured$voteValue)

f1 <- function(x) # calculates the precentage of votes for an option
{
  bla <- table(x)
  return(bla/length(x)*100)
}
voteSummary <- aggregate(data=restructured, voteValue ~ survey + question, FUN = f1)
Environment <- voteSummary$voteValue[2,] - voteSummary$voteValue[1,]
Family <- voteSummary$voteValue[4,] - voteSummary$voteValue[3,]
Firearm <- voteSummary$voteValue[6,] - voteSummary$voteValue[5,]
Immigration <- voteSummary$voteValue[8,] - voteSummary$voteValue[7,]

changeTable <- rbind(Environment, Family, Firearm, Immigration)

plt <- barplot(changeTable, main = "Change when seeing the poll",
        ylab = "Change in %", #ylim = c(-8,10),
        xlab="Popularity of option", col=c("darkblue","red","green","yellow"),
        legend = rownames(changeTable), args.legend = list(x = "topleft", bty = "n"), 
        beside=TRUE)
postscript(file="change.eps", width=6, height=3, paper="special", horizontal=F)

###figure 2
plt
dev.off()

#Bayesian estimates for table 1
restructured$voteInt <- as.numeric(restructured$voteValue)

cmod1 <- brm(voteInt ~ survey * threshold + survey * question + age + sex + (1|subject), 
             data = subset(restructured,restructured$sex != 2),  family="cumulative", sample_prior=T, cores = 2, chains = 2, iter = 1000, control = list(adapt_delta = 0.9))
summary(cmod1, waic=T)
hypothesis(cmod1, c("surveysurvey > 0","thresholdthreshold < 0","thresholdmajorityMrule < 0","questionFamilies < 0","questionFirearms < 0","questionImmigration > 0","age < 0","sex1 < 0","surveysurvey:thresholdthreshold > 0","surveysurvey:thresholdmajorityMrule > 0","surveysurvey:questionFamilies > 0","surveysurvey:questionFirearms < 0","surveysurvey:questionImmigration < 0"))

cmod2 <- brm(voteInt ~ survey * threshold + survey * question + age + sex + pol + (1|subject), 
             data = subset(restructured,restructured$sex != 2),  family="cumulative", sample_prior=T, cores = 2, chains = 2, iter = 1000, control = list(adapt_delta = 0.9))
summary(cmod2, waic=T)
hypothesis(cmod2, c("surveysurvey > 0","thresholdthreshold < 0","thresholdmajorityMrule < 0","questionFamilies < 0","questionFirearms < 0","questionImmigration > 0","age < 0","sex1 < 0","pol < 0","surveysurvey:thresholdthreshold < 0","surveysurvey:thresholdmajorityMrule > 0","surveysurvey:questionFamilies < 0","surveysurvey:questionFirearms < 0","surveysurvey:questionImmigration < 0"))

#save(restructured,file = "/home/mifaab/restructured.Rdata")
